package com.zhongwang.mms.module.purchase.controller;

import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.TWarehouseInfo;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.purchase.model.PurOrderForQueryResultModel;
import com.zhongwang.mms.module.purchase.model.PurWarQueryModel;
import com.zhongwang.mms.module.purchase.service.PurWarQueryService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.DateUtil;
import com.zhongwang.mms.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: 出入库综合查询
 * @Author: China.zh
 * @Date: 2020/4/8 10:23
 */
@Slf4j
@Controller
@RequestMapping("/purWarQuery")
public class PurWarQueryController extends BaseController {

    @Autowired
    private PurWarQueryService purWarQueryService;
    @Autowired
    private LogService logService;
    @Autowired
    private TWarehouseInfoDao warehouseInfoDao;

    /**
     * 页面
     *
     * @return 页面路径
     */
    @GetMapping("/index")
    public String project(Model model) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String start = sdf.format(new Date());
        String end = sdf2.format(new Date());
        model.addAttribute("start",start+"-1");
        model.addAttribute("end",end);
        return "purchase/purWarManage/purWarQuery/page";
    }

    /**
     * 首页跳转页面
     *
     * @return 页面路径
     */
    @GetMapping("/index/{mode}/{totalPrice}/{year}/{month}")
    public String projectJump(Model model,@PathVariable("mode") String mode,@PathVariable("totalPrice") String totalPrice,@PathVariable("year") Integer year,@PathVariable("month") Integer month) {
        model.addAttribute("mode",mode);
        model.addAttribute("totalPrice",totalPrice);
        String start = DateUtil.getFirstDayOfMonth(month);
        start = start.replace(start.substring(0,start.indexOf("-")),year.toString());
        model.addAttribute("start",start.substring(0,10));
        String end = DateUtil.getLastDayOfMonth(month);
        end = end.replace(end.substring(0,end.indexOf("-")),year.toString());
        model.addAttribute("end",end.substring(0,10));
        return "purchase/purWarManage/purWarQuery/page";
    }

    /**
     * 操作列查看按钮
     * 跳转详细页面
     *
     * @return 页面路径
     */
    @GetMapping("/info/{id}")
    public String info(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("odrId", id);
        return "purchase/purWarManage/purWarQuery/info/page";
    }

    /**
     * 列表
     *
     * @param param 查询条件
     * @return list
     */
    @ResponseBody
    @PostMapping("/list")
    @RequiresPermissions({"purwar:purwarquery:view"})
    public JsonResult list(PurWarQueryModel param) {
        // 记录开始时间（纳秒）
        long startTime = System.nanoTime();
        Date startTimeDate = new Date();
        StringBuilder searchCondition = new StringBuilder();
        if(!param.getOdrCode().isEmpty()){
            searchCondition.append("，单据编号：").append(param.getOdrCode());
        }
        if(!param.getOdaProCode().isEmpty()){
            searchCondition.append("，项目编号：").append(param.getOdaProCode());
        }
        if(!param.getOdaProName().isEmpty()){
            searchCondition.append("，项目名称：").append(param.getOdaProName());
        }
        if(!param.getOdaSapCode().isEmpty()){
            searchCondition.append("，SAP物料编码：").append(param.getOdaSapCode());
        }
        if(!param.getOdaMatDesc().isEmpty()){
            searchCondition.append("，物料描述：").append(param.getOdaMatDesc());
        }
        if(!param.getOdaTrackCode().isEmpty()){
            searchCondition.append("，跟踪号：").append(param.getOdaTrackCode());
        }
        if(!param.getName().isEmpty()){
            searchCondition.append("，制单人：").append(param.getName());
        }
        if(!param.getOdrTakePerson().isEmpty()){
            searchCondition.append("，领料人：").append(param.getOdrTakePerson());
        }
        if(!param.getOdaPosition().isEmpty()){
            searchCondition.append("，区位：").append(param.getOdaPosition());
        }
        if(!param.getOdaCaseNo().isEmpty()){
            searchCondition.append("，箱号：").append(param.getOdaCaseNo());
        }
        if(!param.getDepName().isEmpty()){
            searchCondition.append("，领料部门：").append(param.getDepName());
        }
        if(!param.getContractNo().isEmpty()){
            searchCondition.append("，合同编号：").append(param.getContractNo());
        }
        if(param.getOdaWhiId() != null && param.getOdaWhiId() != 0){
            TWarehouseInfo warehouseInfo = warehouseInfoDao.getTWarehouseInfoByWhiId(param.getOdaWhiId());
            searchCondition.append("，仓库：").append(warehouseInfo.getWhiName());
        }else{
            searchCondition.append("，仓库：").append("全部");
        }
        if(param.getInOutType() != null && param.getInOutType() != 0){
            if(param.getInOutType() == 1){
                searchCondition.append("，出入库类型：").append("入库");
            }
            else if(param.getInOutType() == 2){
                searchCondition.append("，出入库类型：").append("出库");
            }
        }else{
            searchCondition.append("，出入库类型：").append("全部");
        }
        if(param.getBillType() != null && param.getBillType() != 0){
            if(param.getBillType() == 1){
                searchCondition.append("，单据类型：").append("采购入库");
            }
            else if(param.getBillType() == 2){
                searchCondition.append("，单据类型：").append("领料出库");
            }
            else if(param.getBillType() == 3){
                searchCondition.append("，单据类型：").append("串料出库");
            }
            else if(param.getBillType() == 4){
                searchCondition.append("，单据类型：").append("调拨出库");
            }
            else if(param.getBillType() == 5){
                searchCondition.append("，单据类型：").append("车间返料");
            }
            else if(param.getBillType() == 6){
                searchCondition.append("，单据类型：").append("串料剩余");
            }
            else if(param.getBillType() == 7){
                searchCondition.append("，单据类型：").append("项目完结剩余");
            }
            else if(param.getBillType() == 8){
                searchCondition.append("，单据类型：").append("调拨入库");
            }
        }else{
            searchCondition.append("，单据类型：").append("全部");
        }
        if(param.getPStartDate()!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            searchCondition.append("，制单时间：").append("开始：").append(sdf.format(param.getPStartDate()));
        }
        if(param.getPEndDate()!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            searchCondition.append("，制单时间：").append("结束：").append(sdf.format(param.getPEndDate()));
        }
        startPage();
        List<PurWarQueryModel> list = purWarQueryService.findPurWarList(param);
        // 记录开始时间（纳秒）
        long endTime = System.nanoTime();
        // 计算耗时（秒）
        double elapsedSeconds = (endTime - startTime) / 1_000_000_000.0;
        Date endTimeDate = new Date();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logService.saveLog("外购件出入库综合查询","查询条件"+searchCondition+",返回查询结果"+list.size()+"条数据，开始查询时间："+sdf1.format(startTimeDate)+"，返回查询结果时间："+sdf1.format(endTimeDate)+"，总耗时"+elapsedSeconds+"秒！");
        return jsonResult(list);
    }

    /**
     * 列表 获取单据内容
     * @param param 查询条件
     * @return list
     */
    @ResponseBody
    @PostMapping("/findOdaListByOdrId")
    @RequiresPermissions({"purwar:purwarquery:view"})
    public JsonResult findOdaListByOdrId(PurWarQueryModel param) {
        PurOrderForQueryResultModel purOrderModel = purWarQueryService.findOrderInfoByOdrId(param);
        return JsonResult.success("",purOrderModel);
    }

    /**
     * 列表 导出
     * @param param 查询条件
     * @return list
     */
    @PostMapping("/exportExcel")
    @ResponseBody
    @RequiresPermissions({"purwar:purwarquery:export"})
    public JsonResult exportExcel(PurWarQueryModel param) {
        return purWarQueryService.exportExcel(param);
    }

    @Value("${user.upload.path}")
    private String uploadPath;
    /**
     * 列表 下载
     * @param excelFileName 下载的文件名
     * @return list
     */
    @GetMapping("/downloadExportExcel/{excelFileName}")
    @ResponseBody
    @RequiresPermissions(value = {"purwar:purwarquery:export","matwar:matwarquery:export","matinv:matinvquery:export","purinv:purinvquery:export",
    "halwar:halwarquery:export","halinv:halinvquery:export","purinv:purchalist:edit"}, logical = Logical.OR)
    public void downloadExportExcel(@PathVariable("excelFileName") String excelFileName, HttpServletResponse response) {
        //获取当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String excelPath = uploadPath + user.getAccount() + "/"+excelFileName;
        FileUtils.downloadFile(excelPath, response);
    }
}
